package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.atguigu.lease.web.admin.vo.fee.FeeValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {
    @Autowired
    private ApartmentFacilityService apartmentFacilityService;
    @Autowired
    private ApartmentLabelService apartmentLabelService;
    @Autowired
    private ApartmentFeeValueService apartmentFeeValueService;
    @Autowired
    private GraphInfoService graphInfoService;
    @Autowired
    private ApartmentInfoMapper apartmentInfoMapper;
    @Autowired
    private ProvinceInfoMapper provinceInfoMapper;
    @Autowired
    private CityInfoMapper cityInfoMapper;
    @Autowired
    private DistrictInfoMapper districtInfoMapper;
    @Autowired
    private GraphInfoMapper graphInfoMapper;
    @Autowired
    private FeeValueMapper feeValueMapper;
    @Autowired
    private LabelInfoMapper labelInfoMapper;
    @Autowired
    private FacilityInfoMapper facilityInfoMapper;
    @Autowired
    private RoomInfoMapper roomInfoMapper;


    /**
     * 1、修改公寓信息
     * 2、新增公寓信息
     *
     * @param apartmentSubmitVo
     */
    @Override
    public void saveOrUpdateApartment(ApartmentSubmitVo apartmentSubmitVo) {

        Long id = apartmentSubmitVo.getId();//这个id是公寓id

        //查询公寓所属的省的信息(名字)
        ProvinceInfo provinceInfo = provinceInfoMapper.selectById(apartmentSubmitVo.getProvinceId());
        apartmentSubmitVo.setProvinceName(provinceInfo.getName());

        //查询公寓所属的城市名字
        CityInfo cityInfo = cityInfoMapper.selectById(apartmentSubmitVo.getCityId());
        apartmentSubmitVo.setCityName(cityInfo.getName());

        //查询 公寓所属的区县名字
        DistrictInfo districtInfo = districtInfoMapper.selectById(apartmentSubmitVo.getDistrictId());
        apartmentSubmitVo.setDistrictName(districtInfo.getName());

        // 1、添加公寓基本信息,基本信息我们用框架给我们封装好的saveOrUpdate方法
        this.saveOrUpdate(apartmentSubmitVo);

        //因为这个方法是修改和添加混用，因此需要判断一下是不是修改
        if (id != null) {
            //如果是修改，就删除和当前公寓有关联的外键配套信息，再添加新的配套信息
            // 1、删除公寓的配套信息
            apartmentFacilityService.remove(new LambdaQueryWrapper<ApartmentFacility>().eq(ApartmentFacility::getApartmentId, id));
            //2、删除公寓的标签信息
            apartmentLabelService.remove(new LambdaQueryWrapper<ApartmentLabel>().eq(ApartmentLabel::getApartmentId, id));
            //3、删除公寓的费用信息
            apartmentFeeValueService.remove(new LambdaQueryWrapper<ApartmentFeeValue>().eq(ApartmentFeeValue::getApartmentId, id));
            //4、删除公寓的图信息
            graphInfoService.remove(new LambdaQueryWrapper<GraphInfo>().eq(GraphInfo::getId, id).eq(GraphInfo::getItemType, ItemType.APARTMENT));
        }
        // 2、添加公寓的相关配套信息
        List<Long> facilityInfoIds = apartmentSubmitVo.getFacilityInfoIds();//获取前端传递过来的所有配套的id集合
        if (!CollectionUtils.isEmpty(facilityInfoIds)) {
            List<ApartmentFacility> apartmentFacilityList = new ArrayList<>();//这个集合用来保存公寓和关系实体对象，也就是组合之后的实体对象
            for (Long facilityInfoId : facilityInfoIds) {
                // 2.1、创建配套信息对象
                ApartmentFacility apartmentFacility = ApartmentFacility.builder().apartmentId(apartmentSubmitVo.getId()).facilityId(facilityInfoId).build();//这里重新获取一次id是因为上面有可能添加信息，添加是没有id的，因此需要重新获取
                apartmentFacilityList.add(apartmentFacility);
            }
            apartmentFacilityService.saveBatch(apartmentFacilityList);//保存配套信息，批量添加
        }
        //添加公寓的标签信息
        List<Long> labelIds = apartmentSubmitVo.getLabelIds();//获取前端传递过来的所有标签的id集合
        if (!CollectionUtils.isEmpty(labelIds)) {
            List<ApartmentLabel> apartmentLabelList = new ArrayList<>();//这个集合用来保存公寓和标签关系实体对象
            for (Long labelId : labelIds) {
                ApartmentLabel apartmentLabel = ApartmentLabel.builder().apartmentId(apartmentSubmitVo.getId()).labelId(labelId).build();
                apartmentLabelList.add(apartmentLabel);
            }
            apartmentLabelService.saveBatch(apartmentLabelList); //保存标签信息，批量添加
        }
        //添加公寓的费用信息
        List<Long> feeValueIds = apartmentSubmitVo.getFeeValueIds();//获取前端传递过来的所有费用信息的id集合
        if (!CollectionUtils.isEmpty(feeValueIds)) {
            List<ApartmentFeeValue> apartmentFeeValueList = new ArrayList<>();//这个集合用来保存公寓和费用信息关系实体对象
            for (Long feeValueId : feeValueIds) {
                ApartmentFeeValue apartmentFeeValue = ApartmentFeeValue.builder().apartmentId(apartmentSubmitVo.getId()).feeValueId(feeValueId).build();
                apartmentFeeValueList.add(apartmentFeeValue);
            }
            apartmentFeeValueService.saveBatch(apartmentFeeValueList); //保存费用信息，批量添加
        }
        //添加公寓的图信息
        List<GraphVo> graphVoList = apartmentSubmitVo.getGraphVoList();//获取前端传递过来的所有图的VO对象集合
        if (!CollectionUtils.isEmpty(graphVoList)) {
            List<GraphInfo> graphInfoList = new ArrayList<>();//这个集合用来保存公寓和图信息关系实体对象
            for (GraphVo graphVo : graphVoList) {
                GraphInfo graphInfo = new GraphInfo();
                graphInfo.setName(graphVo.getName());
                graphInfo.setUrl(graphVo.getUrl());
                graphInfo.setItemId(apartmentSubmitVo.getId());
                graphInfo.setItemType(ItemType.APARTMENT);
                graphInfoList.add(graphInfo);
            }
            graphInfoService.saveBatch(graphInfoList); //保存图信息，批量添加
        }

    }

    /**
     * 根据条件分页查询公寓信息
     *
     * @param page    分页对象
     * @param queryVo 查询条件（携带地区信息）
     * @return 分页结果
     */
    @Override
    public IPage<ApartmentItemVo> pageApartmentItemByQuery(IPage<ApartmentItemVo> page, ApartmentQueryVo queryVo) {
        return apartmentInfoMapper.pageApartmentItemByQuery(page, queryVo);
    }

    /**
     * 根据id查询公寓详情信息
     * 回显方法： 根据公寓的id查询公寓基本信息以及相关信息
     *
     * @param
     * @return
     */
    @Override
    public ApartmentDetailVo getDetailById(Long id) {
        ApartmentDetailVo apartmentDetailVo = new ApartmentDetailVo();//公寓详情信息对象
        //1、查询公寓基本信息
        ApartmentInfo apartmentInfo = this.getById(id);

        BeanUtils.copyProperties(apartmentInfo, apartmentDetailVo);//公寓基本信息拷贝到详情对象中


        //下面的数据都需要自己白那些sql语句，完成自主查询
        //2、查询公寓的图信息
        List<GraphVo> graphInfos = graphInfoMapper.selectListByapartment(id, ItemType.APARTMENT);
        //3、查询公寓的标签信息
        List<LabelInfo> labelInfoList = labelInfoMapper.selectListByapartment(id);
        //4、查询公寓的配套信息
        List<FacilityInfo> facilityInfos = facilityInfoMapper.selectListByapartmentId(id);
        //5、查询公寓的杂费信息
        List<FeeValueVo> feeValues = feeValueMapper.selectListByapartment(id);
        //6、组装数据
        BeanUtils.copyProperties(graphInfos, apartmentDetailVo);
        BeanUtils.copyProperties(labelInfoList, apartmentDetailVo);
        BeanUtils.copyProperties(facilityInfos, apartmentDetailVo);
        BeanUtils.copyProperties(feeValues, apartmentDetailVo);



        return apartmentDetailVo;
    }

    @Override
    public void removeByIdInnfo(Long id) {

        //查询当前被删除的公寓是否有房间信息，如果有就提示不能删除
        Long count = roomInfoMapper.selectCount(new LambdaQueryWrapper<RoomInfo>().eq(RoomInfo::getApartmentId, id));
        if (count > 0) {
            throw new LeaseException(ResultCodeEnum.DELETE_ERROR);
        }
        this.removeById(id);
    }
}




